<template>
    <zt-dialog v-model="visible" :title="titleName" @confirm="confirmBtn" :loading="isLoading" :showFooter="true"
        :showFullScreen="false" width="500px" height="400px" :showConfirm="true">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="80px" class="demo-ruleForm" status-icon
            :disabled="isDisabled">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="ruleForm.roleName" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item label="角色状态" prop="activated">
                <el-radio-group v-model="ruleForm.activated">
                    <el-radio :label="true">激活</el-radio>
                    <el-radio :label="false">禁用</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="角色描述" prop="remark">
                <el-input v-model="ruleForm.remark" type="textarea" />
            </el-form-item>
        </el-form>
    </zt-dialog>
</template>

<script setup>
import ztDialog from '@/components/zt-dialog/index.vue'
import { ElMessage } from 'element-plus'
import { apiPostCreateRole, apiPutUpdateRole } from "@/api/admin/systemSettings/rolesManage/api.js";
import { apiGetDepartmentTree } from "@/api/common/api.js"

const isLoading = ref(false)
const departmentOptions = ref([])
const props = defineProps({
    // 当前类型
    currentType: {
        type: String,
        default: 'add'
    },
    // 控制弹窗显示
    visible: {
        type: Boolean,
        default: false
    },
    // 传递过来的值
    objectValue: {
        type: Object,
        default: () => {
            return {}
        }
    }
})
const emit = defineEmits(['success', 'update:modelValue'])
const ruleFormRef = ref(null)
const ruleForm = reactive({
    roleName: '',// 角色名称
    activated: true,//状态
})
const updateForm = reactive({
    roleId: '',// 角色id
})

const rules = reactive({
    roleName: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
    ],
    activated: [
        {
            required: true,
            message: '请选择状态',
            trigger: 'change',
        },
    ],

})


// 动态获取标题
const titleName = computed(() => {
    switch (props.currentType) {
        case 'edit':
            return '修改角色'
        case 'add':
            return '添加角色'
    }
})

// 是否禁用表单
const isDisabled = computed(() => {
    return props.currentType == 'detail' ? true : false
})

// 子组件定义自己的visible
const visible = computed({
    get: () => props.visible,
    set: (value) => {
        // 清除表单字段值
        Object.keys(ruleForm).forEach(key => {
            if (key == 'activated') {
                ruleForm[key] = true //默认设置为激活
            } else {
                ruleForm[key] = '';
            }
        });
        ruleFormRef.value.clearValidate()
        emit('update:modelValue', value)
    },
})

// 监听传递过来的值 赋值
watch(() => props.objectValue, (e) => {
    if (e) {
        if (props.currentType != 'add') {
            // 遍历 key 相等的赋值 
            Object.keys(e).forEach(item => {
                Object.keys(ruleForm).forEach(ele => {
                    if (item == ele) {
                        ruleForm[ele] = e[item]
                    }
                });
                Object.keys(updateForm).forEach(ele => {
                    if (item == ele) {
                        updateForm[ele] = e[item]
                    }
                });
            });

            // updateForm.roleId = e.roleId
        }
    }
}, {
    deep: true,
    immediate: true
})

// 确认按钮
async function confirmBtn() {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
            // 编辑时执行
            if (props.currentType == 'edit') {
                editChange()
            }
            // 添加时执行
            if (props.currentType == 'add') {
                addChange()//添加
            }

        } else {
            const firstValue = Object.values(fields)[0];
            ElMessage({
                message: firstValue[0].message,
                type: 'warning',
            })
        }
    })
}

// 添加方法
function addChange() {
    isLoading.value = true
    apiPostCreateRole(ruleForm).then(res => {
        if (res.success) {
            ElMessage({
                message: '添加成功',
                type: 'success',
            })
            emit('success')
            visible.value = false
            return false
        }
        ElMessage({
            message: res.message,
            type: 'warning',
        })
    }).finally(() => {
        isLoading.value = false
    })
}

// 编辑方法
function editChange() {
    isLoading.value = true
    apiPutUpdateRole({ ...ruleForm, ...updateForm }).then(res => {
        if (res.success) {
            ElMessage({
                message: '修改成功',
                type: 'success',
            })
            emit('success')
            visible.value = false
            return false
        }
        ElMessage({
            message: res.message,
            type: 'warning',
        })
    }).finally(() => {
        isLoading.value = false
    })
}

// 获取部门列表树数据
function getDeptTreeData() {
    apiGetDepartmentTree({}).then(res => {
        if (res.success) {
            departmentOptions.value = convertToOptions(res.data)
            if (props.currentType != 'add' && ruleForm.depId) {
                let list = convertToOptions(res.data)
                ruleForm.depIdArr = getAllParentValues(list, ruleForm.depId).reverse()
            }
        }
    })
}
// 处理数据
function convertToOptions(data) {
    const options = [];
    function traverse(node) {
        const option = {
            value: node.depId,
            label: node.depName,
            parentId: node.parentId,
        };
        if (node.children && node.children.length > 0) {
            option.children = node.children.map(child => traverse(child));
        }
        return option;
    }
    options.push(traverse(data));
    return options;
}
// 数据处理
function getAllParentValues(arrs, value) {
    for (let i = 0; i < arrs.length; i++) {
        const item = arrs[i];
        if (item.children) {
            // 如果当前节点有子节点，则递归查找子节点
            const parentValues = getAllParentValues(item.children, value);
            if (parentValues.length > 0) {
                // 如果找到了对应的父级value值，则将当前节点的value值添加到父级value值数组中
                parentValues.push(item.value);
                return parentValues;
            }
        }
        if (item.value === value) {
            // 如果当前节点的value值等于目标值，则返回当前节点的value值
            return [item.value];
        }
    }
    // 如果未找到对应的父级value值，则返回空数组
    return [];
}


getDeptTreeData()

</script>

<style lang='scss' scoped></style>
<style lang="scss">
.el-input__wrapper {
    width: 100%;
}
</style>